<template>
  <div>
    <h3>登录页面</h3>
    <el-form :model="ruleUser" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" style="width:500px;margin:0 auto">
        <el-form-item label="请输入用户名或手机号" prop="username">
            <el-input  v-model="ruleUser.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="ruleUser.password" autocomplete="off"></el-input>
        </el-form-item>
    
        <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
            <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
        </el-form-item>
</el-form>

  </div>
</template>

<script>
import axios from 'axios'
  export default {
    data() {
      var validateUsername = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('用户名或密码不能为空'));
        }
        const userRules=/^[a-zA-Z][0-9a-zA-Z]{4,16}$/;
        const mobileRules=/^1[3-9][0-9]{9}$/;
        if(userRules.test(value) | mobileRules.test(value)){
            return callback()

        }else{
            return callback(new Error('用户名或手机号不符合规则'))
        }
      };
      var validatePasword = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } 
        
        const passRules =/^[a-zA-Z][a-zA-Z0-9]{4,15}$/
        if(passRules.test(value)){
            return callback()
        }else{
            return callback(new Error('密码不符合规则'))
        }
      };
      return {
        ruleUser: {
            username:"",
            password: '',
        },
        rules: {
            username: [
            { validator: validateUsername, trigger: 'blur' }
          ],
          password: [
            { validator: validatePasword, trigger: 'blur' }
          ],
          
        }
      };
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            axios.post('http://127.0.0.1:8000/users/login/',this.ruleUser)
            .then(resp=>{
                console.log(resp);
                this.$store.commit('setUser',resp.data.user)
                let user_obj=JSON.stringify(resp.data.user)
                localStorage.getItem('user',user_obj)
                localStorage.getItem('token',resp.data.token)
                this.$router.push('/index')
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>

<style>

</style>